/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.kj.web;

import java.util.List;
import java.util.Map;

import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.service.AreaService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.kj.entity.KjRegion;
import com.jeesite.modules.kj.service.KjRegionService;

/**
 * kjRegionController
 * @author hzy
 * @version 2021-08-08
 */
@Controller
@RequestMapping(value = "${adminPath}/kj/kjRegion")
public class KjRegionController extends BaseController {

	@Autowired
	private KjRegionService kjRegionService;

	@Autowired
	private AreaService areaService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public KjRegion get(String cityCode, boolean isNewRecord) {
		return kjRegionService.get(cityCode, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("kj:kjRegion:view")
	@RequestMapping(value = {"list", ""})
	public String list(KjRegion kjRegion, Model model) {
		model.addAttribute("kjRegion", kjRegion);
		return "modules/kj/kjRegionList";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("kj:kjRegion:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<KjRegion> listData(KjRegion kjRegion) {
		if (StringUtils.isBlank(kjRegion.getParentCode())) {
			kjRegion.setParentCode(KjRegion.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(kjRegion.getCityName())){
			kjRegion.setParentCode(null);
		}
//		upgradeCity();
		List<KjRegion> list = kjRegionService.findList(kjRegion);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("kj:kjRegion:view")
	@RequestMapping(value = "form")
	public String form(KjRegion kjRegion, Model model) {
		// 创建并初始化下一个节点信息
		kjRegion = createNextNode(kjRegion);
		model.addAttribute("kjRegion", kjRegion);
		return "modules/kj/kjRegionForm";
	}


	public void upgradeCity(){
		KjRegion kjRegion = new KjRegion();

//		for (String area: areas
//		) {
//			kjRegion.setParentCode("0002");
//			kjRegion = createNextNode(kjRegion);
//			kjRegion.setCityName(area);
//			kjRegionService.save(kjRegion);
//		}
	}
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("kj:kjRegion:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public KjRegion createNextNode(KjRegion kjRegion) {
		if (StringUtils.isNotBlank(kjRegion.getParentCode())){
			kjRegion.setParent(kjRegionService.get(kjRegion.getParentCode()));
		}
		if (kjRegion.getIsNewRecord()) {
			KjRegion where = new KjRegion();
			where.setParentCode(kjRegion.getParentCode());
			KjRegion last = kjRegionService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				kjRegion.setTreeSort(last.getTreeSort() + 30);
				kjRegion.setCityCode(IdGen.nextCode(last.getCityCode()));
			}else if (kjRegion.getParent() != null){
				kjRegion.setCityCode(kjRegion.getParent().getCityCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (kjRegion.getTreeSort() == null){
			kjRegion.setTreeSort(KjRegion.DEFAULT_TREE_SORT);
		}
		return kjRegion;
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("kj:kjRegion:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated KjRegion kjRegion) {
		kjRegionService.save(kjRegion);
		return renderResult(Global.TRUE, text("保存地区成功！"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("kj:kjRegion:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(KjRegion kjRegion) {
		kjRegionService.delete(kjRegion);
		return renderResult(Global.TRUE, text("删除地区成功！"));
	}

	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("kj:kjRegion:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<KjRegion> list = kjRegionService.findList(new KjRegion());
		for (int i=0; i<list.size(); i++){
			KjRegion e = list.get(i);
			// 过滤非正常的数据
			if (!KjRegion.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getCityCode(), e.getCityName()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("kj:kjRegion:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(KjRegion kjRegion){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		kjRegionService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}

}
